package com.upay.android.controller.fragment;



import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.type.TypeReference;

import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Intent;
import android.content.Loader;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.upay.android.R;
import com.upay.android.controller.activity.FixedPaymentActivity;
import com.upay.android.controller.activity.WeightedPaymentActivity;
import com.upay.android.controller.adapter.GroupAccountArrayAdapter;
import com.upay.android.controller.helper.Keys;
import com.upay.android.core.service.RestService;
import com.upay.android.domain.authentication.AuthenticationToken;
import com.upay.android.domain.group.GroupAccount;
import com.upay.android.domain.group.GroupPolicy;
import com.upay.android.domain.request.EmptyRequest;
import com.upay.android.domain.request.ProtectedRequestHeader;
import com.upay.android.domain.request.RequestBody;
import com.upay.android.domain.request.RequestEnvelope;
import com.upay.android.domain.response.ResponseEnvelope;
import com.upay.android.domain.rest.RestRequest;
import com.upay.android.util.rest.UrlHelper;


public class GroupAccountListFragment extends AbstractListFragment implements LoaderCallbacks<ResponseEnvelope<List<GroupAccount>>> {

	/* ---- Constants ---- */

	/* ---- Instance Variables ---- */
	private GroupAccountArrayAdapter mGroupAccountArrayAdapter = null;
	private OnSignoutListener mCallback = null;

	/* ---- Constructors ---- */
	
	/* ---- Business Methods ---- */
			
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		getContext().setTitle(R.string.mygroups_title);
		getContext().disableMenuButton();
		
		mGroupAccountArrayAdapter = new GroupAccountArrayAdapter(getContext(), new ArrayList<GroupAccount>());
		setListAdapter(mGroupAccountArrayAdapter);

   	
	}
	
	@Override
	public void onStart() {
		super.onStart();
        getLoaderManager().initLoader(0, null, GroupAccountListFragment.this).forceLoad();
	}

    public void onListItemClick(ListView listView, View view, int position, long id) {
        GroupAccount groupAccount = ((GroupAccountArrayAdapter)getListAdapter()).getItem(position);
        Intent intent = null;
        if (GroupPolicy.GROUP_EXACT.equals(groupAccount.getGroup().getGroupPolicy().getId())) {
        	intent = new Intent(getContext(), FixedPaymentActivity.class);
        } else {
        	intent = new Intent(getContext(), WeightedPaymentActivity.class);
        }
        intent.putExtra(GroupAccount.NAME, groupAccount);
        startActivityForResult(intent, 0);
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    	inflater.inflate(R.menu.groupaccountmenu, menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch(item.getItemId()) {
    	case R.id.action_mygroups_add_group:
    		Toast.makeText(getContext(), "Add Group Selected", Toast.LENGTH_SHORT).show();
    		break;
    	case R.id.action_mygroups_refresh:
    		getLoaderManager().restartLoader(0, null, GroupAccountListFragment.this);
    		break;
    	case R.id.action_mygroups_logout:
    		this.logout();
    		break;
    	case android.R.id.home:
    		getContext().finish();
    	default:
    		return super.onOptionsItemSelected(item);
    		
    	}
    	return true;
    }
    
    private void logout() {
    	SharedPreferences sharedPreferences = getContext().getSharedPreferences(Keys.UPAY_PREFERENCES, 0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(Keys.USERID);
        editor.remove(Keys.TOKEN);
        editor.commit();
        
        mCallback.onSignoutSelected();
    }
    
    /* ---- Interfaces ---- */

	@Override
	public Loader<ResponseEnvelope<List<GroupAccount>>> onCreateLoader(int id, Bundle bundle) {
   	    AuthenticationToken authenticationToken = getAuthenticationToken();
   	    RequestEnvelope<ProtectedRequestHeader, EmptyRequest> requestEnvelope = 
   	    	new RequestEnvelope<ProtectedRequestHeader, EmptyRequest>(
   	    		new ProtectedRequestHeader(authenticationToken), 
   	    		new RequestBody<EmptyRequest>());
   	    TypeReference<ResponseEnvelope<List<GroupAccount>>> typeReference = new TypeReference<ResponseEnvelope<List<GroupAccount>>>() {};
   	    RestRequest<ProtectedRequestHeader, EmptyRequest, List<GroupAccount>> restRequest = 
   	    	new RestRequest<ProtectedRequestHeader, EmptyRequest, List<GroupAccount>>(
   	    		UrlHelper.getUrl(getResources(), UrlHelper.GROUP_ACCOUNT), requestEnvelope, typeReference);           	    
   	    RestService<ProtectedRequestHeader, EmptyRequest, List<GroupAccount>> restService =
   	    	new RestService<ProtectedRequestHeader, EmptyRequest, List<GroupAccount>>(
   	    		getActivity().getApplicationContext(), restRequest);
   	    //restService.reset();
   	    return restService;
	}

	@Override
	public void onLoadFinished(Loader<ResponseEnvelope<List<GroupAccount>>> loader, ResponseEnvelope<List<GroupAccount>> responseEnvelope) {
		mGroupAccountArrayAdapter.clear();
		mGroupAccountArrayAdapter.addAll(responseEnvelope.getResponseBody().getResponseObject());
		
		if (isResumed()) {
			setListShown(Boolean.TRUE);
		} else {
			setListShownNoAnimation(Boolean.TRUE);
		}		
	}

	@Override
	public void onLoaderReset(Loader<ResponseEnvelope<List<GroupAccount>>> loader) {
		mGroupAccountArrayAdapter.clear();		
	}
	
    public interface OnSignoutListener {
        public void onSignoutSelected();
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnSignoutListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnSignoutListener");
        }
    }
   	
}

